package com.example.demo.Gmail.Util;

import com.example.demo.Gmail.Handle.GmailHandle;
import com.example.demo.Gmail.Handle.proxyHandler;
import com.example.demo.Gmail.model.UserModel;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.WatchRequest;
import com.google.api.services.plus.model.Person;
import com.google.common.collect.Lists;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.List;

public class MakeUserUtil {

    public static UserModel makeUser(TokenResponse response,String userName) throws GeneralSecurityException, IOException {
        //获取当前用户的historyId
        UserModel user=new UserModel();
        user.setUserName(userName);
        user.setAccessToken(response.getAccessToken());
        user.setRefreshToken(response.getRefreshToken());
        //获取当前用户的historyId
        List list= Lists.newArrayList();
        list.add("SENT");
        list.add("INBOX");
        Gmail service= GmailHandle.service(user);
        WatchRequest watchRequest=new WatchRequest();
        watchRequest.setTopicName("projects/myproject-221302/topics/cne-topic");
        watchRequest.setLabelIds(list);
        watchRequest.setLabelFilterAction("include");
        String historyId=String.valueOf(service.users().watch("me",watchRequest).execute().getHistoryId());
        user.setHistoryId(historyId);

        //获取当前用户的emaiAddress
        Person people= GmailHandle.userInfo(user).people().get("me").execute();
        String emailAddress= people.getEmails().get(0).getValue();
        user.setEmailAddress(emailAddress);
        return user;
    }
}
